package com.offcn.file.controller;

import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import com.offcn.utils.FastDFSClient;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
public class UploadController {


    @Value("${FILE_SERVER_URL}")
    private String FILE_SERVER_URL;

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file){
        //获取文件的扩展名
        String filename = file.getOriginalFilename();
        String extName = filename.substring(filename.lastIndexOf(".")+ 1);
        System.out.println(extName);
        try {
            FastDFSClient client = new FastDFSClient("classpath:fast_client.conf");
            //执行上传
            String addr = client.uploadFile(file.getBytes(), extName);
            String url = FILE_SERVER_URL + addr;
            return new Result(true, StatusCode.OK,url);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"上传失败" + e.getMessage());
        }
    }


    public static void main(String[] args) throws IOException, MyException {
        ClientGlobal.initByProperties("fastdfs-client.properties");
        System.out.println("fastdfs.network_timeout_in_seconds=" + ClientGlobal.g_network_timeout + "ms");
        System.out.println("fastdfs.charset=" + ClientGlobal.g_charset);
        //创建客户端
        TrackerClient tc = new TrackerClient();
        //连接tracker Server
        TrackerServer ts = tc.getConnection();
        if (ts == null) {
            System.out.println("getConnection return null");
            return;
        }
        //获取一个storage server
        StorageServer ss = tc.getStoreStorage(ts);
        if (ss == null) {
            System.out.println("getStoreStorage return null");
        }
        //创建一个storage存储客户端
        StorageClient1 sc1 = new StorageClient1(ts, ss);
        NameValuePair[] meta_list = null; //new NameValuePair[0];
        String item = "E:\\img\\006.png";
        String fileid;
        fileid = sc1.upload_file1(item, "png", meta_list);
        System.out.println("Upload local file " + item + " ok, fileid=" + fileid);
    }
}

